import React, {useEffect, useState} from 'react'
import {Button, Space, message, TreeSelect, Select} from 'antd'
import type {ColumnsType} from 'antd/es/table'
import {ArrowDownOutlined} from '@ant-design/icons'
import moment from 'moment'
import styles from './index.less'
import SearchForm from '@/components/SearchForm'
import Permissions from '@/components/Permissions'
import {getMaterialLedgerList} from '@/service/storage/materialLedger'
import CustomTable from '@/components/Table'
import {getAllParking} from '@/service/storage/archives'
import {translateDataToTree} from '@/utils/common'
import {getCompany} from '@/service/common'
import {getDict} from '@/service/common/dict'
import {downloadDocumentUrl} from '@/service/common/download'

interface DataType {
	monthStartAdd: number
	monthReduceStock: number
	monthStartStock: number
	id: string
	supplierCode: string
	supplierName: string
	serviceType: string
	contacts: string
	status: string
	date: string
}

const formItemLayout = {
	labelCol: {flex: '100px'},
	wrapperCol: {flex: '1'},
}

const fieldNames = {
	label: 'name',
	value: 'id',
	id: 'id',
	pId: 'parentId',
}

const material = (props: any) => {
	const [dataSourse, setDataSourse] = useState<any[]>([])
	const [searchData, setSearchData] = useState({})
	const [companyData, setCompanyData] = useState([])
	const [dictData, setDictData] = useState<any>()
	const [loading, setLoading] = useState(false)
	const [total, setTotal] = useState()
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})
	const [warehouseData, setWarehouseData] = useState<any>([])

	/** 获取所属公司数据 */
	const onCompany = () => {
		getCompany({merchantId: props?.user?.orgId}).then((res: any) => {
			const list = translateDataToTree(res.data)
			setCompanyData(list as any)
		})
	}
	useEffect(() => {
		onCompany()
	}, [props?.user?.orgId])

	/** 获取仓库列表 */
	useEffect(() => {
		getAllParking()
			.then((res: any) => {
				setWarehouseData(res.data)
			})
			.catch(() => {
				setWarehouseData([])
			})
		getDict(
			{
				dictKeys: ['Warehouse_Type'],
			},
			(res: any) => {
				setDictData(res)
			},
		)
	}, [])

	// 获取物料台账列表
	const getData = () => {
		setLoading(true)
		getMaterialLedgerList({
			...params,
			beginTime: moment().format('YYYY-MM-01'),
			endTime: moment().add(1, 'months').format('YYYY-MM-01'),
			...searchData,
		})
			.then((res: any) => {
				if (res?.success) {
					setDataSourse(res?.data?.records)
					setTotal(res?.data?.total)
					setLoading(false)
				} else {
					setLoading(false)
				}
			})
			.catch((err) => {
				setDataSourse([])
				message.error(err)
				setLoading(false)
			})
	}
	useEffect(() => {
		getData()
	}, [params])

	const columns: ColumnsType<DataType> = [
		{
			title: '存货代码',
			dataIndex: 'goodsCode',
			align: 'center',
			width: 150,
		},
		{
			title: '物料名称',
			dataIndex: 'goodsArchivesName',
			align: 'center',
			width: 100,
		},
		{
			title: '本月起初库存',
			dataIndex: 'monthStartStock',
			align: 'center',
			width: 120,
			render: (text) => text || 0,
		},
		{
			title: '本月增加库存',
			dataIndex: 'monthStartAdd',
			align: 'center',
			width: 120,
			render: (text) => text || 0,
		},
		{
			title: '本月减少库存',
			dataIndex: 'monthReduceStock',
			align: 'center',
			width: 120,
			render: (text) => text || 0,
		},
		{
			title: '本月期末库存',
			dataIndex: 'monthExpectStock',
			align: 'center',
			width: 120,
			render: (text: any, record) => {
				const data =
					Number(record?.monthStartStock || 0) +
					Number(record?.monthStartAdd || 0) -
					Number(record?.monthReduceStock || 0)
				return data
			},
		},
		{
			title: '仓库代码',
			dataIndex: 'warehouseCode',
			align: 'center',
			width: 150,
		},
		{
			title: '仓库名称',
			dataIndex: 'warehouseName',
			align: 'center',
			width: 120,
		},
		{
			title: '仓库类型',
			dataIndex: 'warehouseType',
			align: 'center',
			width: 100,
			render: (text) => (
				<Select
					value={text?.toString()}
					disabled
					fieldNames={{value: 'dictKey', label: 'dictValue'}}
					options={dictData?.Warehouse_Type}
				/>
			),
		},
		{
			title: '所属公司',
			dataIndex: 'orgId',
			align: 'center',
			width: 150,
			render: (text) => (
				<>
					{text ? (
						<TreeSelect
							value={text}
							disabled
							dropdownStyle={{maxHeight: 400, overflow: 'auto'}}
							treeDefaultExpandAll
							fieldNames={fieldNames}
							treeDataSimpleMode
							treeData={companyData}
						/>
					) : (
						'-'
					)}
				</>
			),
		},
		{
			title: '城市',
			dataIndex: 'cityName',
			align: 'center',
			width: 100,
		},
	]
	const formItems: any[] = [
		{
			type: 'group',
			key: 'group1',
			groupItems: [
				{
					type: 'time',
					subtype: 'month',
					valueTime: moment(),
					allowClear: false,
					label: '截止时间',
					name: 'currentTime',
					key: 'currentTime',
				},
				{
					type: 'select',
					key: 'warehouseId',
					name: 'warehouseId',
					label: '所属仓库',
					keys: 'id',
					title: 'warehouseName',
					items: warehouseData,
				},
				{
					type: 'select',
					key: 'status',
					name: 'status',
					label: '大分类中分类',
					keys: 'value',
					title: 'title',
					items: [],
				},
			],
		},
		{
			type: 'group',
			key: 'group2',
			groupItems: [
				{
					type: 'input',
					label: '物料代码/名称',
					name: 'keyWords',
					key: 'keyWords',
				},
				{},
				{},
			],
		},
	]
	const onFinish = (values: any) => {
		const searchDatas = {
			...values,
			beginTime: moment(values?.currentTime).format('YYYY-MM-01'),
			endTime: moment(values?.currentTime)
				.add(1, 'months')
				.format('YYYY-MM-01'),
		}
		delete searchDatas.currentTime
		setSearchData(searchDatas)
		setParams({
			current: 1,
			size: 10,
		})
	}

	const onReset = () => {
		setSearchData({})
		setParams({
			current: 1,
			size: 10,
		})
	}
	return (
		<div className={styles.material}>
			<div className={styles.content}>
				<div className={styles.search}>
					<SearchForm
						onFinish={onFinish}
						onReset={onReset}
						formItems={formItems}
						formLayout={formItemLayout}
					/>
				</div>
				<div className={styles.btnlist}>
					<Space size={12}>
						<Permissions permissionID="amc_storage_materialLedger_export">
							<Button
								icon={<ArrowDownOutlined />}
								className={styles.import}
								ghost
								size="small"
								onClick={() => {
									downloadDocumentUrl({
										resourceId: '135',
										queryDesc:
											'物料台账导出,resourceId:135',
										queryParam: Object.keys(searchData)
											?.length
											? searchData
											: {
													beginTime:
														moment().format(
															'YYYY-MM-01',
														),
													endTime: moment()
														.add(1, 'months')
														.format('YYYY-MM-01'),
											  },
									})
								}}>
								导出
							</Button>
						</Permissions>
					</Space>
				</div>
				<CustomTable
					params={params}
					columns={columns}
					total={total}
					pagination
					callback={(pagination: any) => {
						setParams(pagination)
					}}
					loading={loading}
					dataSource={dataSourse}
				/>
			</div>
		</div>
	)
}

export default material
